package com.itheima.wms.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pinda.base.BaseController;
import com.itheima.pinda.base.R;
import com.itheima.pinda.base.entity.SuperEntity;
import com.itheima.wms.dto.OwnerLocationBatchDTO;
import com.itheima.wms.dto.OwnerLocationDTO;
import com.itheima.wms.entity.LocationEntity;
import com.itheima.wms.entity.OwnerLocationEntity;
import com.itheima.wms.entity.OwnerStrategyEntity;
import com.itheima.wms.service.LocationService;
import com.itheima.wms.service.OwnerLocationService;
import com.itheima.wms.service.OwnerStrategyService;
import com.itheima.wms.vo.OwnerLocationDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * 货主-库位关联表
 * </p>
 */
@Slf4j
@RestController
@RequestMapping("/ownerLocation")
@Api(value = "OwnerLocation", tags = "货主-库位关联表")
public class OwnerLocationController extends BaseController {

    @Autowired
    private LocationService locationService;
    @Autowired
    private OwnerLocationService ownerLocationService;
    @Autowired
    private OwnerStrategyService ownerStrategyService;

    /**
     * 分页查询货主-库位关联表
     *
     * @param data 分页查询对象
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询货主-库位关联表", notes = "分页查询货主-库位关联表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", dataType = "long", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示几条", dataType = "long", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "ascs", value = "正序排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "descs", value = "倒叙排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "data", value = "无效参数 字段可以使用前缀控制查询方式 gt_, ge_, lt_, le_, in_, like_, likeRight_, likeLeft_", dataType = "string", paramType = "none"),
            @ApiImplicitParam(name = "ownerId", value = "货主id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "warehouseId", value = "仓库id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "areaId", value = "库区id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "locationId", value = "库位id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createUser", value = "创建人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "createName", value = "创建人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "updateUser", value = "更新人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "updateName", value = "更新人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "logicDel", value = "逻辑删除 0 删除", dataType = "Integer", paramType = "query"),
    })
    @GetMapping("/page")
    public R<IPage<OwnerLocationEntity>> page(@RequestParam Map data) {
        Page<OwnerLocationEntity> page = getPage();
        IPage<OwnerLocationEntity> ownerLocationPage = ownerLocationService.page(page, data);
        page.setRecords(ownerLocationPage.getRecords());
        return success(page);
    }

    /**
     * 分页查询货主-库位关联表 详细
     *
     * @param data 分页查询对象
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询货主-库位关联表 详细", notes = "分页查询货主-库位关联表 详细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "无效参数 字段可以使用前缀控制查询方式 gt_, ge_, lt_, le_, in_, like_, likeRight_, likeLeft_", dataType = "string", paramType = "none"),
            @ApiImplicitParam(name = "ownerId", value = "货主id", dataType = "Long", paramType = "query"),
    })
    @GetMapping("/pageDetail")
    public R<IPage<OwnerLocationDetailVO>> pageDetail(@RequestParam Map data) {
        Page<OwnerLocationDetailVO> page = getPage();
        IPage<OwnerLocationDetailVO> ownerLocationPage = ownerLocationService.pageDetail(page, data);
        page.setRecords(ownerLocationPage.getRecords());
        return success(page);
    }

    @ApiOperation(value = "查询全部货主-库位关联表", notes = "查询全部货主-库位关联表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ascs", value = "正序排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "descs", value = "倒叙排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "data", value = "无效参数 字段可以使用前缀控制查询方式 gt_, ge_, lt_, le_, in_, like_, likeRight_, likeLeft_", dataType = "string", paramType = "none"),
            @ApiImplicitParam(name = "ownerId", value = "货主id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "warehouseId", value = "仓库id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "areaId", value = "库区id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "locationId", value = "库位id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createUser", value = "创建人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "createName", value = "创建人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "updateUser", value = "更新人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "updateName", value = "更新人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "logicDel", value = "逻辑删除 0 删除", dataType = "Integer", paramType = "query"),
    })
    @GetMapping("/list")
    public R<List<OwnerLocationEntity>> list(@RequestParam Map data) {
        List<OwnerLocationEntity> ownerLocationArray = ownerLocationService.list(data);
        return success(ownerLocationArray);
    }

    /**
     * 查询货主-库位关联表
     *
     * @param id 主键id
     * @return 查询结果
     */
    @ApiOperation(value = "查询货主-库位关联表", notes = "查询货主-库位关联表")
    @GetMapping("/{id}")
    public R<OwnerLocationEntity> get(@PathVariable Long id) {
        return success(ownerLocationService.getById(id));
    }

    /**
     * 新增货主-库位关联表
     *
     * @param data 新增对象
     * @return 新增结果
     */
    @ApiOperation(value = "新增货主-库位关联表", notes = "新增货主-库位关联表不为空的字段")
    @PostMapping
    public R<OwnerLocationEntity> save(@RequestBody @Validated(SuperEntity.Save.class) OwnerLocationDTO data) {
        ownerLocationService.save(data);
        return success(data);
    }

    /**
     * 货主批量关联库位
     *
     * @param data 新增对象
     * @return 新增结果
     */
    @ApiOperation(value = "货主批量关联库位", notes = "货主批量关联库位")
    @PostMapping("batch")
    public R<Boolean> batchSave(@RequestBody @Validated(SuperEntity.Save.class) OwnerLocationBatchDTO data) {
        List<LocationEntity> locationEntities = new ArrayList<>();
        List<OwnerLocationEntity> ownerLocationEntities = new ArrayList<>();
        List<OwnerStrategyEntity> ownerStrategyEntities = new ArrayList<>(); // 2.0 优化
        for (String idStr : data.getIdStrArray()) {
            String[] idArray = idStr.split(",");
            OwnerLocationEntity ownerLocationEntity = new OwnerLocationEntity();
            ownerLocationEntity.setOwnerId(data.getOwnerId());
            ownerLocationEntity.setWarehouseId(Long.valueOf(idArray[0]));
            ownerLocationEntity.setAreaId(Long.valueOf(idArray[1]));
            ownerLocationEntity.setLocationId(Long.valueOf(idArray[2]));
            ownerLocationEntities.add(ownerLocationEntity);

            LocationEntity locationEntity = new LocationEntity();
            locationEntity.setId(ownerLocationEntity.getLocationId());
            locationEntity.setOwnerId(data.getOwnerId());
            locationEntities.add(locationEntity);
        }
        if (!CollectionUtils.isEmpty(ownerLocationEntities)) {
            ownerLocationService.saveBatch(ownerLocationEntities);
            locationService.updateBatchById(locationEntities);
            // 2.0 优化 begin
//            Map<Long, OwnerLocationEntity> map = ownerLocationEntities.stream().collect(Collectors.toMap(item -> item.getAreaId(), item -> item, (oldValue, newValue) -> oldValue));
//            map.forEach((key, value) -> {
//                OwnerStrategyEntity ownerStrategyEntity = new OwnerStrategyEntity();
//                ownerStrategyEntity.setOwnerId(value.getOwnerId());
//                ownerStrategyEntity.setWarehouseId(value.getWarehouseId());
//                ownerStrategyEntity.setAreaId(key);
//                ownerStrategyEntity.setInventoryStrategy(0L);
//                ownerStrategyEntity.setLaunchStrategy(0L);
//                ownerStrategyEntity.setPickingStrategy(0L);
//                ownerStrategyEntities.add(ownerStrategyEntity);
//            });
//            ownerStrategyService.saveBatch(ownerStrategyEntities);
            // 2.0 优化 end
        }
        return success(true);
    }

    /**
     * 修改货主-库位关联表
     *
     * @param data 修改对象
     * @return 修改结果
     */
    @ApiOperation(value = "修改货主-库位关联表", notes = "修改货主-库位关联表不为空的字段")
    @PutMapping
    public R<OwnerLocationEntity> update(@RequestBody @Validated(SuperEntity.Update.class) OwnerLocationDTO data) {
        ownerLocationService.updateById(data);
        return success(data);
    }

    /**
     * 删除货主-库位关联表
     *
     * @param ids 主键id
     * @return 删除结果
     */
    @ApiOperation(value = "删除货主-库位关联表", notes = "根据id物理删除货主-库位关联表")
    @DeleteMapping
    public R<Boolean> delete(@RequestParam("ids[]") List<Long> ids) {
        ownerLocationService.removeByIds(ids);
        return success();
    }

}
